package user

import (
	"errors"
	"fiberCommonUtils/request"
	"fmt"
	"github.com/gofiber/fiber/v2"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"mongoDB"
)

type uploadUserKeyWord struct {
	Name   string             `json:"name"`
	P      string             `json:"p"`
	UserID primitive.ObjectID `json:"userID"`
}

func MiddlewareFindUserByLoginName(c *fiber.Ctx) error {
	ctx, cancel := mongoDB.MongoDBTimeoutContext()
	defer cancel()
	data := request.ParsePostLikeRequest(c, &uploadUserLogin{}).(*uploadUserLogin)
	_user := &User{}
	err := _user.FindByLoginName(ctx, &data.Name)
	if err != nil {
		return errors.New(fmt.Sprint("登录信息错误,请核对.", err.Error()))
	}
	c.Locals("user", _user)
	return c.Next()
}

func MiddlewareFindUserByID(c *fiber.Ctx) error {
	ctx, cancel := mongoDB.MongoDBTimeoutContext()
	defer cancel()
	data := request.ParsePostLikeRequest(c, &uploadUserKeyWord{}).(*uploadUserKeyWord)
	_user := &User{}
	err := _user.FindByID(ctx, &data.UserID)
	if err != nil {
		return errors.New(fmt.Sprint("登录信息错误,请核对.", err.Error()))
	}
	c.Locals("user", _user)
	return c.Next()
}
